package com.twan.base.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.util.Base64;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.twan.base.R;
import com.twan.base.entity.NotiMessage;
import com.twan.base.ui.WebViewActivity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import io.reactivex.functions.Consumer;

/**
 * @author Twan
 * @date 2019/3/30
 */
public final class MyUtil {

    @SuppressLint("SetJavaScriptEnabled")
    @SuppressWarnings("deprecation")
    public static WebView setWebView(WebView webView) {
        WebSettings set = webView.getSettings();
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.requestFocus();
        set.setJavaScriptCanOpenWindowsAutomatically(true);
        set.setPluginState(WebSettings.PluginState.ON);
        set.setAllowFileAccess(true);
        set.setJavaScriptEnabled(true);
        set.setUseWideViewPort(true);
        set.setLoadWithOverviewMode(true);
        set.setSupportZoom(true);
        //支持缩放
        set.setBuiltInZoomControls(true);
        set.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        set.setDomStorageEnabled(true);// 自动开启窗口
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        return webView;
    }

    //跳转到浏览器并打开指定页面
    public static void skipBrowser(Activity context, String url){
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        context.startActivity(intent);
    }

    /**
     * 请求类型
     * @return String
     */
    public static String getContentType(){
        return "application/x-www-form-urlencoded";
    }

    /**
     * 转base64
     * @param path
     * @return
     */
    public static String encodeBase64File2(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();

        //base64 encode
        String encodeString = Base64.encodeToString(bytes,Base64.DEFAULT);
        String encode = URLEncoder.encode(encodeString);
        //LogUtil.d("encode="+encode);
        return encode;
    }


    public static String bitmapToBase64(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String encodeBase64File(String path){
        try {
            FileInputStream fis = new FileInputStream(path);//转换成输入流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while((count = fis.read(buffer)) >= 0){
                baos.write(buffer, 0, count);//读取输入流并写入输出字节流中
            }
            fis.close();//关闭文件输入流
            String uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));  //进行Base64编码
            return uploadBuffer;
        } catch (Exception e) {
            return null;
        }

    }


    //创建本地通知
    public static void showLocalNotification(Context context,NotiMessage message) {
        NotificationManager mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        createNotificationChannel(mNotifyManager,"0", "易来赚推送", NotificationManager.IMPORTANCE_HIGH);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "0");
        mBuilder.setContentTitle(message.getData().getTitle())
                .setLargeIcon(GlideUtils.loadBitmap(context,message.getData().getImg()))
                .setSmallIcon(R.drawable.jpush_notification_icon);
        mBuilder.setContentText(message.getData().getDesc());
        mBuilder.setAutoCancel(true);
        Intent openIntent = new Intent(context, WebViewActivity.class);
        openIntent.putExtra("title",message.getData().getTitle());
        openIntent.putExtra("url",message.getData().getUrl());
        openIntent.putExtra("id",message.getData().getId());
        openIntent.putExtra("type","2");//推送广告
        PendingIntent pendingintent = PendingIntent.getActivity(context, 0, openIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(0, mBuilder.build());
    }

    @TargetApi(Build.VERSION_CODES.O)
    public static void createNotificationChannel(NotificationManager mNotifyManager, String channelId, String channelName, int importance) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
            // 配置通知渠道的属性
            channel.setDescription("易来赚推送");
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            channel .enableLights(true);
            channel .setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            channel .enableVibration(true);
            channel .setVibrationPattern(new long[]{100, 200, 300,400});
            mNotifyManager.createNotificationChannel(channel);
        }
    }


    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNum 电话号码
     */
    public static void callPhone(final Activity context, final String phoneNum) {
        requestPermission(context, new RxPermissionsUtil.PermissionListener() {
            @Override
            public void onSucces() {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + phoneNum);
                    intent.setData(data);
                    context.startActivity(intent);
                }
            }
        }, Manifest.permission.CALL_PHONE);

    }

    //use rxpermission
    public static void requestPermission(final Activity context, final RxPermissionsUtil.PermissionListener listener, String... permissions) {
        try {
            RxPermissions rxPermissions = new RxPermissions(context);
            rxPermissions.request(permissions) //Manifest.permission.CAMERA
                    .subscribe(new Consumer<Boolean>() {
                                   @Override
                                   public void accept(Boolean aBoolean) throws Exception {
                                       if (aBoolean) {
                                           if (listener != null) {
                                               listener.onSucces();
                                           }
                                       } else {
                                           ToastUtil.shortShow("请开启权限");
                                       }
                                   }
                               }
                    );
        } catch (Exception e) {
            //rx bug: getFragmentManager may be null , should be getSupportFragmentManager()
            LogUtil.e(e.toString());
        }
    }
}
